package cn.diancan.Tags.utils;

import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.util.Map;

public class FreeMarkerParam2VoUtil {
	
	/**
	 * 将map里面的参数对象 封装到 请求 bean
	 * @param clazz
	 * @param param 
	 * @return
	 * @throws Exception
	 */
	public static <T> T param2Vo(Class<T> clazz, Map<String,Object> param ) throws  Exception {
		T vo = clazz.newInstance();
		
		BeanInfo binfo = Introspector.getBeanInfo(clazz, Object.class);
		PropertyDescriptor[] propertys = binfo.getPropertyDescriptors();
		for (PropertyDescriptor property : propertys) {
			
			Method ms = property.getWriteMethod();
			Method methodget = property.getReadMethod();
			Class c= methodget.getReturnType();
			String elename = property.getName();
			
			Object p= param.get(elename) ;
			if(null != p){
				if("java.lang.String".equals(c.getName())  ){
					ms.invoke(vo, p.toString()  );
				}else if("java.lang.Integer".equals(c.getName()) ||"int".equals(c.getName()) ){
					ms.invoke(vo, Integer.valueOf(p.toString())  );
				}else if("java.lang.Double".equals(c.getName()) || "double".equals(c.getName())){
					ms.invoke(vo, Double.valueOf(p.toString())   );
				}else if("java.lang.Float".equals(c.getName())  || "float".equals(c.getName())){
					ms.invoke(vo, Float.valueOf(p.toString())  );
				}else if("java.lang.Long".equals(c.getName()) || "long".equals(c.getName()) ){
					ms.invoke(vo, Long.valueOf(p.toString())  );
				}else{//如果都不是   抛异常
					ms.invoke(vo, p.toString()  );
					//throw new Exception("类型转换失败" );
				}
			} 
		} 
	   return	vo;
		
	}

}
